/**
 * Created by zhanglihe on 15/11/3.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'model',
    'dialog',
    'datepicker',
    'validation'
], function ($, common, ready, template, Model, dialog, datepicker, Validation) {

    var index = function () {
        this.init();
    };

    index.prototype = {
        init: function () {
            var _this = this;
            //服务商
            $.ajax({
                url: _global.url.api + 'agencys',
                data: {limit: 1000, level: 'level45'},
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('agency', res.data);
                    }
                }
            });
            //地区
            $.ajax({
                url: _global.url.api + 'regions',
                type: 'get',
                async: false,
                data: {depth: 2},
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('region', res.data);
                    }
                }
            });

            this.fetch();
            this.event();
        },
        fetch: function () {
            var that = this;
            var id = getUrlPath(4);
            this.model = new Model({
                url: _global.url.api + 'site/' + id,
                data: {},
                render: function () {
                    console.log(this.data);
                    $('#main-view').html(template('edit-tpl', {
                        agency: that.agency,
                        region: that.region,
                        site: this.data
                    }));
                }
            });
            this.model.fetch();

            //表单验证
            this.validation = new Validation({
                rules: {
                    name: {required: true},
                    mobile: {required: true, mobile: true}
                }
            });
            /////////level_list客户级别分类重置
            $("#level_list").prop("value", $("#level_list").prop("title"));
        },
        set: function ($k, $v) {
            this[$k] = $v;
        },
        event: function () {
            var _this = this;

            //日期下拉
            $('.short_date').on('click', function () {
                WdatePicker({
                    el: this.id,
                    dateFmt: 'yyyy-MM-dd'
                });
            });
            //地区联动
            $('.province').on('change', function () {
                $('select[name="city"]').html('');
                var id = $(this).val();
                var city = _this.region[id].child;
                for (var n in city) {
                    $('select[name="city"]').append('<option value="' + city[n].id + '">' + city[n].name + '</option>')
                }
            });
            if (_this.model.data.province > 0) {
                var city = _this.region[_this.model.data.province].child;
                for (var n in city) {
                    var selected = '';
                    if (_this.model.data.city == city[n].id) {
                        selected = 'selected';
                    }
                    $('select[name="city"]').append('<option value="' + city[n].id + '" ' + selected + '>' + city[n].name + '</option>')
                }
            }

            $('input,select,textarea').on('change', function (e) {
                _this.change(e);
            });

            //保存事件
            $('#btn-save').on('click', function (e) {
                e.preventDefault();
                _this.model.data.expired_at = $('input[name="expired_at"]').val();
                _this.model.data.kf_enabled = $('input[name="kf_enabled"]').is(':checked') ? 1 : 0;

                if (_this.validation.isFail()) {
                    return false;
                }

                _this.model.data.is_oversea = $('input[name="is_oversea"]').is(':checked') ? 1 : 0;
                _this.model.data.is_baoming = $('input[name="is_baoming"]').is(':checked') ? 1 : 0;
                _this.model.data.allow_agency_login = $('input[name="allow_agency_login"]').is(':checked') ? 1 : 0;
                _this.model.data.allaw_agency_view_data = $('input[name="allaw_agency_view_data"]').is(':checked') ? 1 : 0;
                _this.model.data.kehu_type = $('#type').val();
                console.log(_this.model.data);
                if (_this.model.put()) {
                    window.location.reload();
                }
            });

            //选择分类
            $('#btn-cate').on('click', function (e) {
                e.preventDefault();
                //一级分类
                _this.cate_form = $(template('cate-tpl', {}));
                //分类
                $.ajax({
                    url: _global.url.api + 'categorys',
                    type: 'get',
                    async: false,
                    data: {depth: 1},
                    success: function (res) {
                        if (res.code == 0) {
                            $.each(res.data, function (n, v) {
                                _this.cate_form.find('[name="cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                            });
                        }
                    }
                });
                //显示二级分类，并联动
                //bind change event
                _this.cate_form.find('[name="cate"]').on('change', function () {
                    _this.cate_form.find('[name="child-cate"]').html('');
                    var id = typeof $(this).val() == 'object' ? $(this).val()[0] : $(this).val();

                    $.ajax({
                        url: _global.url.api + 'categorys',
                        type: 'get',
                        async: false,
                        data: {depth: 1, pid: id},
                        success: function (res) {
                            if (res.code == 0) {
                                $.each(res.data, function (n, v) {
                                    _this.cate_form.find('[name="child-cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                                });
                            }
                        }
                    });
                });
                //显示弹框
                _this.dialog = dialog({
                    content: _this.cate_form,
                    width: 400,
                    ok: function () {
                        $.each(_this.cate_form.find('select[name="child-cate"]')[0].selectedOptions, function (n, option) {
                            if ($('#' + option.value).text()) {
                                Alert({msg: '不能选择相同的分类', type: 'error'});
                                return false;
                            }
                            var el_cate = $('<span class="label label-info mr10" id="' + option.value + '">' + option.text +
                            ' <a href="" style="color: #fff"><span class="glyphicon glyphicon-remove"></span></a></span>');
                            $('#cate-name').append(el_cate);
                            _this.change_cate(option.value, 'add');
                        });
                        _this.cate_form.remove();

                    }, cancel: function () {
                    }
                }).show(e.target);
            });

            //分类删除
            $('body').on('click', '#cate-name a', function (e) {
                e.preventDefault();
                $(this).parent().remove();
                _this.change_cate($(this).parent().attr('id'), 'del');
            });
        },
        change: function (e) {
            this.model.data[$(e.target).attr('name')] = $(e.target).val();
        },

        /**
         * 更改cate_id
         *
         * @param id
         * @param method (add: 增加, del: 移除)
         */
        change_cate: function (id, method) {
            var _this = this;
            //初始化cate_id
            if (typeof _this.model.data.cate_id == 'undefined') {
                _this.model.data.cate_id = [];
                $.each(_this.model.data.category_relation, function () {
                    _this.model.data.cate_id.push(this.cate_id);
                });
            }
            if (method == 'add') {
                _this.model.data.cate_id.push(id);
            } else {
                _this.model.data.cate_id.remove(id);
            }
        }
    };

    new index();

});